package com.dykj.fireFighting.web.firemanger;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.video.entity.PartitionsVideo;
import com.dykj.fireFighting.api.base.video.service.IPartitionsVideoService;
import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.PartitionsDevice;
import com.dykj.fireFighting.api.socialUnit.devicemanger.service.IPartitionsDeviceService;
import com.dykj.fireFighting.api.socialUnit.firemanger.dto.FireStationDto;
import com.dykj.fireFighting.api.socialUnit.firemanger.entity.CoordinateRelation;
import com.dykj.fireFighting.api.socialUnit.firemanger.entity.FireStation;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.ICoordinateRelationService;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.IFireStationDeviceService;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.IFireStationService;
import com.dykj.fireFighting.api.socialUnit.firemanger.vo.FireStationDeviceVo;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


import javax.validation.Valid;



/**
 * 消防管理-消防站接口
 *
 * @Author aixiaolan
 * @Date  2021-06-24 13:27:38
 */
@Slf4j
@Api(value = "消防管理-消防站接口", tags = {"消防管理-消防站接口"})
@RestController
@RequestMapping("firemanger/fireStation")
public class FireStationController {

    @DubboReference
    private IFireStationService fireStationService;

    @DubboReference
    private IFireStationDeviceService fireStationDeviceService;

    @DubboReference
    private ICoordinateRelationService coordinateRelationService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    @DubboReference
    private IPartitionsVideoService partitionsVideoService;
    @DubboReference
    private IPartitionsDeviceService partitionsDeviceService;

    /**
     * 获取单位id
     * @return String
     */
    public String getEnterpriseId() {
        try {
            return Long.toString(ShiroUtil.getUser().getEnterpriseId());
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }

    /**
     * 获取用户名称
     * @return String
     */
    public String getName() {
        try {
            return ShiroUtil.getUser().getName();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }
    /**
     * 消防管理-消防站列表
     *
     * @return
     */
    @AutoLog(value = "消防管理-消防站-分页列表查询")
    @ApiOperation(value = "消防管理-消防站分页列表", notes = "消防管理-消防站分页列表")
    @GetMapping("/list")
//    @RequiresPermissions("firemanger/fireStation/list")
    public CommonResult<PageVo<FireStation>> treeGrid(FireStationDto commonDto) {
        commonDto.setUnitId(getEnterpriseId());
        PageVo<FireStation> page = fireStationService.pageList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 获取消防管理-消防站信息
     */
    @AutoLog(value = "消防管理-消防站-获取消防管理-消防站信息")
    @ApiOperation(value = "获取消防管理-消防站信息", notes = "获取消防管理-消防站信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
//    @RequiresPermissions("firemanger/fireStation/info")
    public CommonResult<FireStationDeviceVo> info(@PathVariable("id") String id){
        FireStation fireStation = fireStationService.getById(id);

        FireStationDeviceVo fireStationDeviceVo=new FireStationDeviceVo();
        BeanUtils.copyProperties(fireStation,fireStationDeviceVo);
        List<String> device=fireStationDeviceService.getFireStationDeviceById(id,0);
        List<String> deviceTradtion=fireStationDeviceService.getFireStationDeviceById(id,1);
        //fireStationDeviceVo.setDevice(device);
        fireStationDeviceVo.setDeviceTradition(deviceTradtion);
        if(StringUtils.isNotBlank(fireStationDeviceVo.getPartitionId())){
            PartitionsDevice point = partitionsDeviceService.getPoint(fireStationDeviceVo.getPartitionId(), id);
            log.info("分区关系表查询结果：{}",point.toString());
            if(point!=null){
                fireStationDeviceVo.setLat( point.getX());
                fireStationDeviceVo.setLng(point.getY());
            }
        }else{
            //关系表查找经纬度
            List<CoordinateRelation> coordinateRelations=coordinateRelationService.getByTableId(id,"0");
            log.info("关系表查询结果条数：{}",coordinateRelations.size());
            if(coordinateRelations.size()>0){
                fireStationDeviceVo.setLat( coordinateRelations.get(0).getLat());
                fireStationDeviceVo.setLng(coordinateRelations.get(0).getLng());
            }
        }
        log.info("查询结果：{}",fireStationDeviceVo.toString());
        return CommonResult.success(fireStationDeviceVo);
    }

    /**
     * 保存消防管理-消防站信息
     */
    @AutoLog(value = "消防管理-消防站-保存消防管理-消防站信息")
    @ApiOperation(value = "保存消防管理-消防站信息", notes = "保存消防管理-消防站信息")
    @PostMapping("/save")
//    @RequiresPermissions("firemanger/fireStation/save")
    public CommonResult save(@Valid @RequestBody FireStationDeviceVo fireStation) {
        try {
            fireStation.setCreateBy(getName());
            fireStation.setUnitId(getEnterpriseId());
            fireStationService.insertFireStation(fireStation);
            log.info("经度：【{}】,纬度：【{}】",fireStation.getLng(),fireStation.getLat());
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改消防管理-消防站信息
     */
    @AutoLog(value = "消防管理-消防站-修改消防管理-消防站信息")
    @ApiOperation(value = "修改消防管理-消防站信息", notes = "修改消防管理-消防站信息")
    @PostMapping("/update")
//    @RequiresPermissions("firemanger/fireStation/update")
    public CommonResult update(@Valid @RequestBody FireStationDeviceVo fireStation) {
        try {

            fireStation.setUpdateBy(getName());
            fireStationService.updateFireStation(fireStation);
            log.info("经度：【{}】,纬度：【{}】",fireStation.getLng(),fireStation.getLat());
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除消防管理-消防站信息
     */
    @AutoLog(value = "消防管理-消防站-删除消防管理-消防站信息")
    @ApiOperation(value = "删除消防管理-消防站信息", notes = "删除消防管理-消防站信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
//    @RequiresPermissions("firemanger/fireStation/delete")
    public CommonResult delete(@RequestBody String[]ids) {
        try {
                fireStationService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    @AutoLog(value = "根据单位ID获取单位图片")
    @ApiOperation(value = "单位ID获取单位图片", notes = "单位ID获取单位图片")
    @GetMapping("/getByUnitId")
    public CommonResult<String> getByUnitId() {
        String picture=fireStationService.getPictureByUnitId(getEnterpriseId());
        return CommonResult.success(picture);
    }


    @AutoLog(value = "查询消防站、危险源、重点部位的坐标")
    @ApiOperation(value = "查询消防站、危险源、重点部位的坐标", notes = "查询消防站、危险源、重点部位的坐标")
    @GetMapping("/getCoordinateByUnitId")
    public CommonResult<Map<String,Object>> getCoordinateByUnitId() {
        List<CoordinateRelation> temp=coordinateRelationService.getCoordinateByUnitId(getEnterpriseId());
        Map<String,Object> map=new HashMap<>();
        map.put("data",temp);
        Enterprise enterprise=enterpriseService.getById(ShiroUtil.getUser().getEnterpriseId());
        map.put("unitImg",enterprise.getFireControlPicture());
        map.put("unitInfo",enterprise);
        //QueryWrapper<PartitionsVideo> queryWrapper1=new QueryWrapper();
        //queryWrapper1.eq("unit_id",getEnterpriseId());
        //List<PartitionsVideo> videoList=partitionsVideoService.list(queryWrapper1);
        //map.put("partitionsVideoList",videoList);
        return CommonResult.success(map);
    }

}
